<template>
	<view class="nav">
		<scroll-view class="tabs" scroll-x="true" scroll-with-animation :scroll-left="scrollLeft">
			<view class="tabs-scroll">
				<view class="tabs-scroll_item" style="-webkit-flex: 1;flex: 1;" v-for=" (item,index) in itemList"
					:key="index" :class="{'active':selectIndex==index}" @click="chenked(index)">{{item.title}}
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { getCurrentInstance, onMounted, ref, watch } from "vue";
	const scrollLeft = ref<number>(0)
	const selectIndex = ref<number>(0)
	const itemList = ref<Array<ItabItem>>()
	interface ItabItem {
		title : string
		width ?: number
		left ?: number
		id : number
	}
	interface Iprops {
		tabData : Array<ItabItem>
		defaultSelectIndex ?: number
	}

	const props = withDefaults(defineProps<Iprops>(), {
		tabData: () => [],
		defaultSelectIndex: 6
	})
	const emits = defineEmits<{
		(e : 'select', index : number, item : ItabItem) : void
	}>()
	const chenked = (index : number) => {
		selectIndex.value = index
		scrollLeft.value = 0
		for (let i = 0; i < index - 2; i++) {
			scrollLeft.value = scrollLeft.value + itemList.value[i]?.width
		}
		emits('select', index, props.tabData[index])
	}
	onMounted(() => {
		const query = uni.createSelectorQuery().in(getCurrentInstance());

		query.selectAll('.tabs-scroll_item').boundingClientRect((data : Array<UniApp.NodeInfo>) => {
			let dataLen = data.length;
			for (let i = 0; i < dataLen; i++) {
				//  scroll-view 子元素组件距离左边栏的距离
				itemList.value[i].left = data[i].left;
				//  scroll-view 子元素组件宽度
				itemList.value[i].width = data[i].width
			}
		}).exec()


	})
	watch(() => [props.tabData, props.defaultSelectIndex], () => {
		itemList.value = props.tabData
		selectIndex.value = props.defaultSelectIndex
		if (props.defaultSelectIndex !== 0) {
			setTimeout(() => {
				chenked(props.defaultSelectIndex)
			}, 50)
		}
	}, {
		immediate: true
	})
</script>
<style lang="scss" scoped>
	.nav {
		z-index: 99;
		width: 100%;
		align-items: center;
		flex-wrap: nowrap;
		box-sizing: border-box;
		justify-content: center;
	}

	.tabs {
		flex: 1;
		overflow: hidden;
		box-sizing: border-box;
	}

	.tabs-scroll {
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
		box-sizing: border-box;
	}

	.tabs-scroll_item {
		line-height: 70rpx;
		flex-shrink: 0;
		display: flex;
		justify-content: center;
		color: rgba(41, 43, 53, 0.8);
		font-size: 28rpx;
	}

	.active {
		position: relative;
		color: rgba(0, 0, 0, 1);
		font-weight: 800;
		font-size: 30rpx;
		border-radius: 50rpx;
		box-sizing: border-box;
	}

	.active::after {
		content: "";
		position: absolute;
		width: 50rpx;
		height: 8rpx;
		box-sizing: border-box;
		background-color: #333;
		border-radius: 40rpx !important;
		left: 0px;
		right: 0px;
		bottom: 0px;
		margin: auto;
	}

	/* 隐藏滚动条，但依旧具备可以滚动的功能 */
	::v-deep.uni-scroll-view::-webkit-scrollbar {
		display: none
	}
</style>